<template>
  <div class="download-link-container">
    <div class="header-section">
      <h3 class="title">粘贴共享链接下载文件</h3>
      <p class="subtitle">快速解析Cloud-Drive链接并立即下载文件</p>
    </div>

    <!-- 链接输入区域 -->
    <div class="input-section">
      <el-input
          v-model="shareLink"
          placeholder="请粘贴通过Cloud-Drive分享的完整链接内容"
          type="textarea"
          :rows="3"
          class="link-input"
          @paste="handlePaste"
      >
        <template #prepend>
          <el-icon><Link /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 解析按钮 -->
    <div class="button-section">
      <el-button
          type="primary"
          @click="parseLink"
          :loading="parsing"
          class="parse-btn"
          :icon="parsing ? null : StarFilled"
      >
        <span v-if="!parsing">解析链接</span>
        <span v-else>正在解析中...</span>
      </el-button>
    </div>

    <!-- 解析结果展示 -->
    <div v-if="fileInfo" class="file-info-card">
      <div class="file-info-header">
        <el-icon><Document /></el-icon>
        <h4>检测到共享文件</h4>
      </div>

      <div class="file-info-content">
        <div class="file-info-item">
          <span class="file-info-label">文件ID：</span>
          <span class="file-info-value">{{ fileInfo.fileId }}</span>
        </div>
        <div class="file-info-item">
          <span class="file-info-label">提取码：</span>
          <span class="file-info-value extract-code">{{ fileInfo.extractCode }}</span>
          <el-button
              type="text"
              class="code-copy-btn"
              @click="copyExtractCode"
          >
            <el-icon><CopyDocument /></el-icon>
          </el-button>
        </div>
        <div class="file-info-item">
          <span class="file-info-label">文件名称：</span>
          <span class="file-info-value">{{ fileInfo.fileName }}</span>
        </div>
      </div>

      <div class="download-section">
        <el-button
            type="success"
            @click="downloadFile"
            :loading="downloading"
            class="download-btn"
            :icon="downloading ? null : Download"
        >
          <span v-if="!downloading">立即下载</span>
          <span v-else>下载中...</span>
        </el-button>
      </div>
    </div>

    <!-- 错误提示 -->
    <div class="error-container">
      <el-alert
          v-if="errorMessage"
          type="error"
          :title="errorMessage"
          show-icon
          class="error-alert"
          description="请检查链接格式或网络连接，然后重试"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  Download, Document, CopyDocument,
  StarFilled, Link
} from '@element-plus/icons-vue'
import { downloadFromHDFSApi } from '@/utils/API/file-core/Index.js'
import { ElMessage } from 'element-plus'
import { hideLoading, showLoading } from "@/utils/LoadingUtil";
import { useClipboard } from '@vueuse/core'

// 响应式数据
const shareLink = ref('')
const fileInfo = ref(null)
const errorMessage = ref('')
const parsing = ref(false)
const downloading = ref(false)

// 正则表达式
const LINK_REGEX = /Cloud-Drive内地址:([\w]+)\s*提取码:([\w]+)\s*文件名称:([^\s]+)/i

// 处理粘贴事件
const handlePaste = (e) => {
  setTimeout(() => {
    if (shareLink.value) parseLink()
  }, 100)
}

// 解析链接
const parseLink = async () => {
  const { copy } = useClipboard()
  parsing.value = true
  errorMessage.value = ''
  fileInfo.value = null

  try {
    if (!shareLink.value.trim()) {
      throw new Error('链接内容不能为空')
    }

    const match = shareLink.value.match(LINK_REGEX)
    if (!match) {
      throw new Error('无效的共享链接格式，请检查链接是否包含"Cloud-Drive内地址:xxx 提取码:xxx 文件名称:xxx"内容')
    }

    fileInfo.value = {
      fileId: match[1],
      extractCode: match[2],
      fileName: match[3]
    }
    ElMessage.success('链接解析成功！')
  } catch (err) {
    errorMessage.value = err.message
  } finally {
    parsing.value = false
  }
}

// 复制提取码
const copyExtractCode = () => {
  const { copy } = useClipboard()
  copy(fileInfo.value?.extractCode)
  ElMessage.success('提取码已复制到剪贴板')
}

// 复制链接
const copyToClipboard = () => {
  const { copy } = useClipboard()
  copy(shareLink.value)
  ElMessage.success('链接已复制到剪贴板')
}

// 下载文件
const downloadFile = async () => {
  showLoading()
  try {
    await downloadFromHDFSApi(fileInfo.value.fileId, fileInfo.value.fileName)
  } catch (e) {
    ElMessage.error("文件下载错误" || e.message)
  } finally {
    hideLoading()
  }
}

// 组件挂载时自动读取剪贴板
onMounted(async () => {
  try {
    const clipboardText = await navigator.clipboard.readText()
    if (clipboardText) {
      shareLink.value = clipboardText
      await parseLink()
    }
  } catch (err) {
    ElMessage.warning('自动读取剪贴板失败，请手动粘贴链接')
  }
})
</script>

<style scoped>
.download-link-container {
  max-width: 600px;
  margin: 32px auto;
  padding: 28px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transition: transform 0.3s ease;
}

.download-link-container:hover {
  transform: translateY(-3px);
}

.header-section {
  text-align: center;
  margin-bottom: 28px;
}

.title {
  margin-bottom: 8px;
  color: #303133;
  font-size: 22px;
  font-weight: 600;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.input-section {
  position: relative;
  margin-bottom: 20px;
}

.link-input {
  margin-bottom: 0;
}

.copy-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  color: #409EFF;
}

.button-section {
  margin-bottom: 24px;
}

.parse-btn {
  width: 100%;
  font-size: 16px;
  border-radius: 8px;
}

.file-info-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.file-info-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.file-info-header h4 {
  margin-left: 8px;
  font-size: 16px;
  color: #606266;
}

.file-info-content {
  margin-bottom: 16px;
}

.file-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.file-info-label {
  color: #909399;
  font-size: 14px;
  min-width: 80px;
}

.file-info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
}

.extract-code {
  margin-right: 10px;
}

.code-copy-btn {
  color: #409EFF;
  font-size: 16px;
  margin-left: 10px;
}

.download-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.download-btn {
  flex: 1;
  font-size: 16px;
  border-radius: 8px;
}

.file-info-link {
  margin-left: 16px;
  font-size: 14px;
}

.error-container {
  margin-top: 16px;
}

.error-alert {
  border-radius: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .download-link-container {
    padding: 20px;
  }

  .download-btn {
    margin-right: 10px;
  }

  .file-info-link {
    display: block;
    margin-top: 10px;
    text-align: center;
  }
}
</style>